const BaseDictMaker = require('./base_dict_maker')
const DictHeader = require('./dict_header')
const utils = require('../utils')
const fs = require('fs')
const path = require('path')


class TextDictMaker extends BaseDictMaker {
    async parse() {
        if (!this.header_) return null
        if (this.header_.isTextParts()) {
            return await this.parsePartsTextDict();
        }
        return this.parseSingleTextDict();
    }

    parseSingleTextDict() {
        let txtContents = this.header_.getContents()
        if (!txtContents.startsWith('\n')) txtContents = '\n' + txtContents
        txtContents = txtContents.replace(/\r/g, '')

        const words = []

        const itemBegin = '\n@word:';
        // find \n@index:\n
        // if cannot find, is the last one
        let lastFoundPos = txtContents.indexOf(itemBegin);
        let i = 1;
        while (lastFoundPos != -1) {
            const foundPos = txtContents.indexOf(itemBegin, lastFoundPos + itemBegin.length)
            const itemTxt = txtContents.substring(lastFoundPos, foundPos == -1 ? txtContents.length : foundPos);
            const header = new DictHeader(itemTxt, 'content')

            const wordInfo = header.getJson();
            wordInfo.index = String(i);
            words.push(wordInfo)


            lastFoundPos = foundPos >= 0
                ? foundPos
                : -1;
            ++i;
        }
        return words;
    }

    parsePartsTextDict() {
        const isDebug = this.isDebugMode();
        return new Promise(async (resolve, reject) => {
            let debugRange = [1, 10]
            if (isDebug) {
                const setting_path = path.join(utils.dictHomeDir(), 'setting.json');
                const settingStr = fs.readFileSync(setting_path, { encoding: 'utf-8' })
                try {
                    const settingJson = JSON.parse(settingStr)
                    if (settingJson.debugRange) {
                        debugRange[0] = settingJson.debugRange[0] || 1
                        debugRange[1] = settingJson.debugRange[1] || 1
                        if (debugRange[1] < debugRange[0]) debugRange[1] = debugRange[0] + 1
                    }
                } catch (e) { }
            }

            const words = [];
            let read_count = 0;
            let total_count = 100000000;
            let begin = 1;
            let end = 100000000;
            let reading_count = 0;
            // if (isDebug) {
            //     begin = debugRange[0]
            //     end = debugRange[1]
            //     total_count = end - begin + 1;
            // }

            for (let i = begin; i <= end; ++i) {
                // if (this.options_ && this.options_.debug && i > 10) break;
                const itemPath = path.join(this.dict_folder_, `parts/${i}.txt`);
                if (!fs.existsSync(itemPath)) {
                    total_count = i - begin;
                    if (read_count >= total_count) {
                        resolve(words);
                    }
                    break;
                }

                while (reading_count >= 500) {
                    await this.wait(1)
                }

                ++reading_count;
                (function (i) {
                    fs.readFile(itemPath, { encoding: 'utf-8' }, (err, data) => {
                        --reading_count;
                        ++read_count;
                        if (err) {
                            return reject(err);
                        }
                        const txtContents = data;
                        const header = new DictHeader(txtContents, 'content')
                        const wordInfo = header.getJson();
                        wordInfo.index = String(i);
                        words[i - 1] = wordInfo
                        if (read_count >= total_count) {
                            resolve(words);
                        }
                    })
                })(i);
            }
        });
    }
}

module.exports = TextDictMaker;